import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { detail } from '@/types/home'

export const useCartStore = defineStore(
  'cart',
  () => {
    // state
    const cartList = ref<detail[]>([])

    // 获取购物车列表
    const getCartList = computed(() => cartList.value)

    // 加入购物车
    const addToCart = (goods: detail) => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        // 之前有，则数量+你传递过来的数量
        oldGoods.number += goods.number
      } else {
        //没有，则push到新数组中
        cartList.value.push(goods)
      }

      // console.log('---cartList---', cartList.value)
    }
    //更改单选状态
    const changeState = (goods: { proid: string; state: boolean }) => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.state = goods.state
      }
    }
    //更改数量
    const changeNumber = ({
      proid,
      number
    }: {
      proid: string
      number: number
    }) => {
      const oldGoods = cartList.value.find(item => item.proid === proid)
      if (oldGoods) {
        oldGoods.number = number
      }
    }
    //计算总价
    const getTotalPrice = computed(() => {
      return cartList.value
        .filter(item => item.state)
        .reduce((total, item) => total + item.number * item.price, 0)
    })
    //计算获取选中的数量
    const getAcount = computed(() => {
      return cartList.value
        .filter(item => item.state)
        .reduce((total, item) => total + item.number, 0)
    })
    //删除商品
    const deleteGoods = (proid: string) => {
      const index = cartList.value.findIndex(item => item.proid === proid)
      if (index > -1) {
        cartList.value.splice(index, 1)
      }
    }
    //是否全部选中
    const isSlectAll = computed(() => {
      return cartList.value.every(item => item.state)
    })
    //
    const selectNotAll = (e: any) => {
      cartList.value.forEach(item => {
        item.state = e.detail
      })
    }
    return {
      cartList,
      getCartList,
      addToCart,
      changeState,
      changeNumber,
      getTotalPrice,
      getAcount,
      deleteGoods,
      selectNotAll,
      isSlectAll
    }
  },
  {
    persist: {
      key: 'cartList', // 存储在小程序 storage 中的key
      storage: {
        // key就是存储的key，值是就是你操作仓库之后的值
        setItem (key, value) {
          uni.setStorageSync(key, value)
        },
        getItem (key) {
          console.log('---getItem---', key)
          return uni.getStorageSync(key)
        }
      }
    }
  }
)
